package com.htjx.mall.admin.controllers;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.htjx.mall.commons.api.CommonConstant;
import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.product.Catalog;
import com.htjx.mall.commons.models.product.Product;
import com.htjx.mall.commons.models.product.Specification;
import com.htjx.mall.commons.utils.Dates;
import com.htjx.mall.services.CatalogService;
import com.htjx.mall.services.ProductService;
import com.htjx.mall.services.SpecificationService;

@Controller
@RequestMapping("/admin/specification")
public class _SpecificationController {
	@Autowired
	private ProductService productService;
	@Autowired
	private CatalogService catalogService;
	@Autowired
	private SpecificationService specificationService;
	
	@RequestMapping(value="/add/{catalog_id}", method = RequestMethod.GET)
	public String add(@PathVariable("catalog_id") long catalog_id, Model model) {
		Specification specification = new Specification();
		specification.setCatalog_id(catalog_id);
		model.addAttribute("specification", specification);
		return "specification/add";
	}
	
	@RequestMapping(value="/add", method = RequestMethod.POST)
	public String add(Specification specification,@RequestParam("img_file") MultipartFile imgFile, Model model, HttpServletRequest request) {
		String name = specification.getName();
		if(StringUtils.isBlank(name)) {
			model.addAttribute("result", new Result(9,"请填写规格名称"));
			return "specification/add";
		}
		
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isBlank(originalFileName)) {
			model.addAttribute("result", new Result(9,"请上传商品图片"));
			return "specification/add";
		}
		
		if(!checkImage(imgFile)) {
			model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
			return "specification/add";
		}
		
//		String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
//		String filePath = "/images/product/"+Dates.toYYYY_MM_DD(new Date());
//		String realPath = request.getSession().getServletContext().getRealPath(filePath); 
//	    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
//			
//		String fileName = Dates.toTimeString(new Date()) + fileType;
//        try {
//			FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, fileName));
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} 
//      specification.setImage(filePath+"/"+fileName);
		specification.setImage(saveImage(imgFile, request));
		
		specification.setCreate_time(new Date());
		specificationService.insertOne(specification);
		return "redirect:/admin/catalog/detail/"+specification.getCatalog_id();
	}
	
	@RequestMapping(value = "/detail/{specification_id}", method = RequestMethod.GET)
	public String specificationDetail(@PathVariable("specification_id") long id, Model model) {
		Specification specification = specificationService.selectById(id);
		Result result = null;
		if(specification == null) {
			result = new Result(9,"查询商品规格失败");
		}
		
		Catalog catalog = catalogService.selectById(specification.getCatalog_id());
		if(catalog == null) {
			result = new Result(9,"对应的商品品类失败");
		} 
		Product product = productService.findUniqueBy("id", String.valueOf(catalog.getProduct_id()));
		
		model.addAttribute("result", result);
		model.addAttribute("product", product);
		model.addAttribute("catalog", catalog);
		model.addAttribute("specification", specification);
		return "specification/detail";
	}
	
	@RequestMapping(value="/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") long id, Model model) {
		Specification specification = specificationService.selectById(id);
		model.addAttribute("specification", specification);
		return "specification/update";
	}
	
	@RequestMapping(value="/update", method = RequestMethod.POST)
	public String update(Specification specification, @RequestParam(value = "img_file", required=false) MultipartFile imgFile, Model model, HttpServletRequest request) {
		String name = specification.getName();
		if(StringUtils.isBlank(name)) {
			model.addAttribute("result", new Result(9,"请填写规格名称"));
			return "specification/update";
		}
		
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isNotBlank(originalFileName)) {
			if(!checkImage(imgFile)) {
				model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
				return "specification/update";
			}
			
//			String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
//			String filePath = "/images/product/"+Dates.toYYYY_MM_DD(new Date());
//			
//			String realPath = request.getSession().getServletContext().getRealPath(filePath); 
//		    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
//				
//			String fileName = Dates.toTimeString(new Date()) + fileType;
//	        try {
//				FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, fileName));
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} 
//	        specification.setImage(filePath+"/"+fileName);
			specification.setImage(saveImage(imgFile, request));
		} 
		
		specification.setCreate_time(new Date());
		specificationService.updateOne(specification);		
		return "redirect:/admin/specification/detail/"+specification.getId();
	}
	
	@RequestMapping(value="/delete/{catalog_id}/{id}")
	public String delete(@PathVariable("id") long id, @PathVariable("catalog_id") long catalog_id) {
		specificationService.deleteOne(id);
		return "redirect:/admin/catalog/detail/"+catalog_id;
	}
	
	private String saveImage(MultipartFile imgFile, HttpServletRequest request) {
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		String fileType = imgFile.getOriginalFilename().substring(originalFileName.lastIndexOf("."));
		String filePath = CommonConstant.SHARE_PATH+Dates.toYYYY_MM_DD(new Date())+"/images";
		String realPath = request.getSession().getServletContext().getRealPath(filePath); 
	    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
			
		String fileName = Dates.toTimeString(new Date()) + fileType;
        try {
			FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, fileName));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
        String image_src = filePath+"/"+fileName;
        return image_src;
	}
	
	private boolean checkImage(MultipartFile imgFile) {
//		long size = imgFile.getSize();
//		if(size == 0 || size > 800000){
//			return false;
//		}
		
		return true;
	}
}
